package com.toprs.base.config

import com.auth0.jwt.exceptions.JWTDecodeException
import com.auth0.jwt.exceptions.TokenExpiredException
import com.toprs.base.annotation.Slf4j2
import com.toprs.base.annotation.Slf4j2.Companion.log
import com.toprs.base.utils.JwtUtil
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.core.annotation.Order
import org.springframework.stereotype.Component
import org.springframework.web.servlet.HandlerInterceptor

@Component
@Order(1)
@Slf4j2
class JwtInterceptor : HandlerInterceptor {


    private fun handleError(request: HttpServletRequest, response: HttpServletResponse, msg: String) {
        response.status = 403
        val writer = response.writer
        writer.println(msg)
        log.info("请求 Method:{} Url:{}, Result:{}", request.method, request.requestURI, msg)
        writer.close()
    }

    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {

        response.characterEncoding = "utf-8"
        val token = request.getHeader("Authorization")
        if (token == null) {
            handleError(request, response, "Please set token!")
            return false
        }

        try {
            val res = JwtUtil.verify(token)
            RequestHolder.setUsername(res["username"].toString())
            RequestHolder.setUserId(res["userId"].toString())
        } catch (e: JWTDecodeException) {
            handleError(request, response, "Token error")
            return false
        } catch (e: TokenExpiredException) {
            handleError(request, response, "Token expired")
            return false
        }


        return super.preHandle(request, response, handler)
    }

}